package com.jd.security.config;

import java.util.Collection;
import java.util.Iterator;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import com.alibaba.fastjson.JSON;

/**
 * 这个类主要是处理用户在访问某个URL的时候，就会通过访问该类的权限与登录用户所拥有的权限做比较，如果拥有权限，
 * 那你就可以到访问外星文明了，如果没有权限，那你就要被遣送回非洲，还会抛一个异常告诉你，你已经被遣送回非洲！
 * @author xiazhengjiao
 */
public class CustomAccessDecisionManager implements AccessDecisionManager {

	@Override
	public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
		if (null == configAttributes) {  
            return;  
        }  
		System.out.println("AccessDecisionManager:"+JSON.toJSONString(configAttributes));
		System.out.println("authentication:"+JSON.toJSONString(authentication));
		Iterator<ConfigAttribute> ite = configAttributes.iterator();
		while (ite.hasNext()) {
			ConfigAttribute ca = ite.next();
			String needRole = ((org.springframework.security.access.SecurityConfig) ca).getAttribute();
			for (GrantedAuthority ga : authentication.getAuthorities()) {
				if (ga.getAuthority().equals(needRole)) {
					// 匹配到有对应角色,则允许通过
					return;
				}
			}
		}
		// 该url有配置权限,但是当然登录用户没有匹配到对应权限,则禁止访问
		throw new AccessDeniedException("not allow");
	}

	@Override
	public boolean supports(ConfigAttribute attribute) {
		return true;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}

}
